package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page=roleDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Role findById(Integer id) {

        return roleDao.findById(id);
    }

    @Override
    public List<Integer> findMenuIdsByRoleId(Integer id) {

        return roleDao.findMenuIdsByRoleId(id);
    }

    @Override
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        return roleDao.findPermissionIdsByRoleId(id);
    }

    @Override
    public void edit(Role role, Integer[] menuIds, Integer[] permissionIds) {
        roleDao.deleteMenuAssociation(role.getId());
        roleDao.deletePermissionAssociation(role.getId());
        setRoleAndMenuAssociation(role.getId(),menuIds);
        setRoleAndPermissionAssociation(role.getId(),permissionIds);
        roleDao.edit(role);

    }

    @Override
    public void add(Role role, Integer[] menuIds, Integer[] permissionIds) {
        roleDao.add(role);
        setRoleAndMenuAssociation(role.getId(),menuIds);
        setRoleAndPermissionAssociation(role.getId(),permissionIds);
    }

    @Override
    public void delete(Integer id) {
        roleDao.deleteMenuAssociation(id);
        roleDao.deletePermissionAssociation(id);
        roleDao.delete(id);
    }

    private void setRoleAndPermissionAssociation(Integer id, Integer[] permissionIds) {
        if(permissionIds!=null&&permissionIds.length>0){
            for (Integer permissionId : permissionIds) {
                Map<String,Integer> map=new HashMap<>();
                map.put("roleId",id);
                map.put("permissionId",permissionId);
                roleDao.setRoleAndPermission(map);
            }
        }
    }

    private void setRoleAndMenuAssociation(Integer id, Integer[] menuIds) {
        if(menuIds!=null&&menuIds.length>0){
            for (Integer menuId : menuIds) {
                Map<String,Integer> map=new HashMap<>();
                map.put("roleId",id);
                map.put("menuId",menuId);
                roleDao.setRoleAndmenu(map);
            }
        }
    }
    /*赵世杰*/
    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }


}
